package com.yisoo.ubag.iot.service.impl;

import com.yisoo.common.utils.R;
import com.yisoo.ubag.iot.aliyun.sdk.openapi.PubManager;
import com.yisoo.ubag.iot.constant.TopicConstant;
import com.yisoo.ubag.iot.entity.BoxRelBagEntity;
import com.yisoo.ubag.iot.entity.DeviceEntity;
import com.yisoo.ubag.iot.service.DeviceService;
import com.yisoo.ubag.iot.util.MqttDataMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yisoo.common.utils.PageUtils;
import com.yisoo.common.utils.Query;

import com.yisoo.ubag.iot.dao.DevRelOrderDao;
import com.yisoo.ubag.iot.entity.DevRelOrderEntity;
import com.yisoo.ubag.iot.service.DevRelOrderService;


@Service("devRelOrderService")
public class DevRelOrderServiceImpl extends ServiceImpl<DevRelOrderDao, DevRelOrderEntity> implements DevRelOrderService {


    @Autowired
    DeviceService deviceService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<DevRelOrderEntity> page = this.page(
                new Query<DevRelOrderEntity>().getPage(params),
                new QueryWrapper<DevRelOrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public Integer checkBagUsing(Long devId, Integer bagId) {
        DevRelOrderEntity entity = baseMapper.selectById(bagId);
        if(entity == null){
//            为空，自己生成一个
            DevRelOrderEntity devRelOrderEntity = new DevRelOrderEntity(
                    bagId.longValue(),devId,devId,0,0,0,null
            );
            baseMapper.insert(devRelOrderEntity);
            return 0;
        }else{
            return entity.getIsUsing();
        }
//        return null;
    }

    @Override
    public R getBagStatus(String bagId) {

        DevRelOrderEntity orderEntity = baseMapper.selectById(bagId);
        return R.ok().put("data",orderEntity.getBagStatus());
    }

    @Override
    public R updateBagStatus(Long bagId, Integer data) {
//        控制背包的开关
        DeviceEntity deviceEntity = deviceService.getById(bagId);
        if (deviceEntity == null) {
            return R.error("设备丢失");
        }
        String content;
        if(data == 1){
            //开背包
            content = MqttDataMapping.getDataPack(201);
        }
        else{
            //关背包
            content = MqttDataMapping.getDataPack(202);
        }
        PubManager.PubRequest(
                content,
                deviceEntity.getProductKey(),
                TopicConstant.getTopicString(deviceEntity.getProductKey(),deviceEntity.getDeviceName(),TopicConstant.SubOrder),
                0
        );
        return R.ok();
    }




}